# Copyright (c) 2020 Presto Labs Pte. Ltd.
# Author: xguo

import datetime
import json

import matplotlib.pyplot as plt
import pandas as pd

from absl import app, flags

flags.DEFINE_string('config', None, 'config file.')
flags.DEFINE_string('oe', None, 'order event file.')


def get_hs_time(timestamp):
  return datetime.datetime.fromtimestamp(timestamp / 1e9).strftime('%Y%m%d %H:%M:%S.%f')


def save_to_file(fn, obj):
  with open(fn, 'w') as ofile:
    json.dump(obj, ofile, indent=2)


def get_sign(side):
  if 'BUY' in side:
    return +1
  elif 'SELL' in side:
    return -1
  else:
    raise ValueError()


def extract_submit(data, product):
  result = []

  for each in data:
    each = each['data']
    if (each['type'] != 'ORDER_EVENT'):
      continue

    if (each['event']['type'] != 'ORDER_SUBMITTED'):
      continue

    if (each['event']['symbol'] != product):
      continue

    event = each['event']
    submit = {
        'symbol': event['symbol'],
        'timestamp': event['event_time'],
        'order_price': event['order_price'],
        'type': event['type'],
    }
    result.append(submit)

  return result


def main(argv):
  with open(flags.FLAGS.config) as infile:
    config = json.load(infile)

  with open(flags.FLAGS.oe) as infile:
    data = json.load(infile)

  product = config['symbol']
  col = extract_submit(data, product)
  save_to_file('submit.json', col)
  print(len(col))
  df = pd.DataFrame(col)
  df.timestamp = pd.to_datetime(df.timestamp.astype(int), unit='ns')
  plt.plot(df.timestamp, df.order_price, marker='.', label='Submit')
  plt.show()


if __name__ == "__main__":
  app.run(main)
